package com.ygqh.baby.kids.handler;

import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.http.URLParameter;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.http.YgRequestExecutor;
import com.ygqh.baby.http.YgResponse;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: sunshuo
 * @Date: 2019/3/5 14:50
 * @Version: 1.0
 */
@Component
public class KidsHttpClient {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private final YgRequestExecutor request = new YgRequestExecutor();

	public JSONObject get(String url, Map<String, String> params) throws YgHttpException {
		List<URLParameter> parameterList = null;
		if (MapUtils.isNotEmpty(params)) {
			parameterList = new ArrayList<>(params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				parameterList.add(new URLParameter(entry.getKey(), entry.getValue()));
			}
		}
		YgResponse response = request.get(url, parameterList == null ? null : parameterList.toArray(new URLParameter[0]));
		JSONObject asJson = response.getAsJson();
		if (!"200".equals(asJson.getString("code"))) {
			logger.error("[getBiOrderDayFromKids] code=" + asJson.getString("msg"));
			throw new YgHttpException("response message is error. message code: " + asJson.getString("code"));
		}
		return asJson;
	}
}
